package com.xu.book.servlet;


import com.xu.book.bean.BookType;
import com.xu.book.service.IBookTypeService;
import com.xu.book.service.impl.BookTypeServiceimpl;
import com.xu.sys.servlet.BaseServlet;
import com.xu.sys.utils.Constant;
import com.xu.sys.utils.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@WebServlet(name = "bookTypeServlet",urlPatterns = {"/book/bookTypeServlet"})
public class BookTypeServlet extends BaseServlet {
    private IBookTypeService service = new BookTypeServiceimpl();
    @Override
    public void list(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        super.list(req, resp);
        service.listPage(pageUtils);
        req.setAttribute(Constant.LIST_PAGE_UTILS,pageUtils);
        req.getRequestDispatcher("/book/bookType/list.jsp").forward(req,resp);

    }

    @Override
    public void saveOrUpdatePage(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String id = req.getParameter(Constant.PARAMETER_ID);
        if (StringUtils.isNotEmpty(id)){
            //更新操作
            BookType entity = service.findById(Integer.parseInt(id));
            req.setAttribute(Constant.UPDATE_ENTITY,entity);
        }
        //进入更新或者添加的页面
        req.getRequestDispatcher("/book/bookType/addOrUpdate.jsp").forward(req,resp);
    }

    @Override
    public void saveOrUpdate(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //获取表单提交的数据
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String notes = req.getParameter("notes");
        BookType type = new BookType();
        type.setName(name);
        type.setNotes(notes);
        if (StringUtils.isNotEmpty(id)){
            type.setId(Integer.parseInt(id));
            service.updateById(type);
        }else {
            service.save(type);
        }
        //重新定向 重新查询查询
        resp.sendRedirect("/book/bookTypeServlet?action=list");
    }



    @Override
    public void remove(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String id = req.getParameter(Constant.PARAMETER_ID);
        service.deleteById(Integer.parseInt(id));
        PrintWriter writer = resp.getWriter();
        writer.write("ok");
        writer.flush();
    }

    @Override
    public void findById(HttpServletRequest req, HttpServletResponse resp) throws Exception {

    }
}
